<?php


namespace app\admin\controller\jizhan;

use app\admin\model\HtnsActivity;
use app\admin\model\HtnsActivityProduct;
use app\admin\model\HtnsActivityProductCate;
use app\admin\model\HtnsProduct;
use app\admin\traits\Curd;
use app\api\services\ActivityProductService;
use app\common\controller\AdminController;
use app\model\product\product\StoreProduct;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\Exception;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站-新UI-换购专区")
 */
class BuyMoreRecommended extends AdminController
{

    use Curd;
    // 活动列表url
    public $activityUrl = '/api/activity_list?type=admin';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsActivityProduct();
        $this->activityUrl = request()->domain().$this->activityUrl;
        $this->assign('activityUrl' , $this->activityUrl);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        $activityId = 9;
        $this->assign('activityId', $activityId);
        // 活动列表
        $whereA['status'] = 1;
        $whereA['delete_time'] = 0;
        $activityList = HtnsActivity::where($whereA)->select()->toArray();
        $activityListArr = array_column($activityList , 'name' ,'id');
        $this->assign('activityList',$activityListArr);
        // 分类列表
        $cateList = HtnsActivityProductCate::where($whereA)->select()->toArray();
        $cateListArr = array_column($cateList , 'name' ,'id');
        $this->assign('cateList',$cateListArr);
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if (isset($filterArr['status'])) {
                    $whereArr[] = ['status', '=', $filterArr['status']];
                }
                if (isset($filterArr['activity_name'])) {
                    $whereArr[] = ['htns_activity_id', '=', $filterArr['activity_name']];
                }
                if (isset($filterArr['cate_name'])) {
                    $whereArr[] = ['cate_id', '=', $filterArr['cate_name']];
                }
            }
            if ($export) {
                $page  = 1;
                $limit = 10000;
            }
            $whereArr[] = ['htns_activity_id','=',9];
            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $whereA['status'] = 1;
            $whereA['delete_time'] = 0;
            $htnsActivity = HtnsActivity::where($whereA)->select()->toArray();
            $htnsActivityName = array_column($htnsActivity , 'name' , 'id');

            $wherep['is_show'] = 1;
            $wherep['is_del'] = 0;
            $storeProduct = HtnsProduct::where($wherep)->column('store_name','id');
            $time = time();
            foreach ($list as &$v) {
                $v['product_name'] = isset($storeProduct[$v['product_id']]) ? $storeProduct[$v['product_id']] : '';
                $v['type'] = empty($v['type']) ? '否' : '是';
                $v['cate_name'] = '';
                $v['activity_name'] = isset($htnsActivityName[$v['htns_activity_id']]) ? $htnsActivityName[$v['htns_activity_id']] : '';
                $htnsActivityProductCate       = HtnsActivityProductCate::find($v['cate_id']);
                if ($htnsActivityProductCate) {
                    $v['cate_name'] = $htnsActivityProductCate['name'];
                }
                $v['activity_end_time'] = '';
                if($v['end_time']){
                    $times = $v['end_time'] - $time;
                    $day = floor($times/86400);// 天数
                    $v['activity_end_time'] = $day.'天';
                }
            }
            // 导出
            if ($export) {
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $activityId = 9;
        $this->assign('activityId', $activityId);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $activityProductService = new ActivityProductService();

                $rev = $activityProductService->checkProductStock($post['product_id'],$post['stock']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }
                $rev = $activityProductService->checkProductIsActivity($post['product_id']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }

                // 默认值
                $product = HtnsProduct::find($post['product_id']);

                $post['image'] = $product['image'];
                $post['product_name'] = $product['store_name'];
//                $post['intro'] = $product['store_info'];
                $post['one_buy_limit_num'] = 9999;
                $post['all_buy_limit_num'] = 9999;
                // 折扣专区
                $post['cate_id'] = 0;
                $post['htns_activity_id'] = 9;
                $post['day_stock'] = 9999;
                $post['sum_stock'] = 9999;

                $post['start_time'] = time();
                $post['end_time'] = $post['start_time'] + 7 * 3600 * 24;//默认参与活动7天时间
                $save = $this->model->save($post);
            } catch (Exception $e) {
                $this->error('保存失败2:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败3');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $activityId = 8;
        $this->assign('activityId', $activityId);
        $row = $this->model->find($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $activityProductService = new ActivityProductService();

                $rev = $activityProductService->checkProductStock($post['product_id'],$post['stock']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }
                $rev = $activityProductService->checkProductIsActivity($post['product_id'] , $id);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }

                $save = $row->save($post);
            } catch (Exception $e) {
                $this->error('保存失败2:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败3');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    // 有效商品列表
    /**
     * @NodeAnotation(title="有效商品列表")
     */
    public function product_list()
    {
        $ret['code'] = 1;
        $ret['msg']  = '获取成功';
        $ret['data'] = [];

        $where[]     = ['is_show', '=', 1];
        $where[]     = ['is_del', '=', 0];
        $htnsProduct = HtnsProduct::where($where)->order('id desc')->select()->toArray();
        if ($htnsProduct) {
            foreach ($htnsProduct as $v) {
                $retv          = [
                    'id'         => $v['id'],
                    'store_name' => $v['store_name'],
                    'store_info' => $v['id'] . '-' . $v['store_name'],
                ];
                $ret['data'][] = $retv;
            }
        }
        return json($ret);
    }

}